//
//  ChooseImageRootViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-9-25.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "ChooseImageRootViewController.h"
#import "XuanpianTaocanCell.h"
#import "OrderSuccessViewController.h"
@interface ChooseImageRootViewController ()

@end

@implementation ChooseImageRootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];

    if (_needFresh) {
        [self getDataWithDict:@{@"OrderID": _orderID} api:API_CHOOSEIMAGEROOT];
    }

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.titleLabel.text = @"选片";

    self.contentView.backgroundColor = BGCOLOR;

    dataDict = [[NSMutableDictionary alloc] init];
    
    _needFresh = YES;

    backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-UI_NAVIGATION_BAR_HEIGHT)];
    [self.contentView addSubview:backScrollView];

    topBtn = [UIButton initButton:CGRectMake(10, 10, UI_SCREEN_WIDTH-20, 40) btnNorImage:nil btnHighlightImage:nil btnTitle:nil titleColor:[UIColor orangeColor] titleFont:[UIFont systemFontOfSize:16]];
    if ([dataDict[@"AllPhoto"] intValue] == 1) {
        [topBtn setTitle:@"浏览全部底片" forState:UIControlStateNormal];
    }else{
        [topBtn setTitle:@"浏览并选择底片" forState:UIControlStateNormal];
    }
    topBtn.backgroundColor = [UIColor whiteColor];
    topBtn.layer.masksToBounds = YES;
    topBtn.layer.cornerRadius = 5;
    topBtn.layer.borderColor = RGBA(200, 200, 200, 1).CGColor;
    topBtn.layer.borderWidth = .5f;
    [topBtn addTarget:self action:@selector(topBtnClick) forControlEvents:UIControlEventTouchUpInside];



    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-UI_NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    myTableView.dataSource = self;
    myTableView.delegate = self;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    myTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:myTableView];


    downView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 100)];
    downView.backgroundColor = [UIColor clearColor];

    UIImage * image = [UIImage imageNamed:@"xiadan"];  //上左下右
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(10,10,10,10)];

    UIButton * btn = [UIButton initButton:CGRectMake(50, 30, UI_SCREEN_WIDTH-100, 40) btnNorImage:image btnHighlightImage:image btnTitle:@"选片完成" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    //    btn.backgroundColor = [UIColor orangeColor];
    [btn addTarget:self action:@selector(chooseImageIsOK) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:btn];
    
    downView.hidden = YES;

    myTableView.tableFooterView = downView;

}

-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

        
        if ([api isEqualToString:API_CHOOSEIMAGEOK]) {
            //提交订单
            if ([tempDic[@"status"] intValue] == 1) {
                OrderSuccessViewController * success = [[OrderSuccessViewController alloc] init];
                success.type = @"chooseImage";
                [self.navigationController pushViewController:success animated:YES];
            }else{
                [XDTools showTips:@"提交订单失败" toView:self.contentView];
            }
            
        }else{
            
            if([[tempDic objectForKey:@"status"]intValue] == 1){
                
                DDLOG(@"dic = %@",tempDic);
                
                dataDict = [NSMutableDictionary dictionaryWithDictionary:tempDic[@"data"]];
                
                //选片完成
                if ([dataDict[@"Selected"] intValue] == 2) {
                    baseIsOK = YES;
                    haveAddress = YES;
                    myTableView.tableFooterView = nil;
                }else if ([dataDict[@"Selected"] intValue] == 0) {
                    //未选片
                    if ([dataDict[@"AllPhoto"] intValue]) {
                        baseIsOK = YES;
                    }else{
                        baseIsOK = NO;
                    }
                }else{
                    //选择部分底片
                    baseIsOK = YES;
                    if ([dataDict[@"ReceiveAddr"] intValue]) {
                        haveAddress = YES;
                    }else{
                        haveAddress = NO;
                    }
                }
                
                downView.hidden = NO;
                
                [myTableView reloadData];
                
            }else{
                [XDTools showTips:tempDic[@"msg"] toView:self.view];
            }
            
        }

    }];

    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}


#pragma mark - UITableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2+[dataDict[@"list"] count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (!section) {
        return 0;
    }else{
        return 20;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * header = [UIView initViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 20) andBackGroudColor:[UIColor clearColor]];
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!indexPath.section) {
        return 60;
    }else if (indexPath.section == [dataDict[@"list"] count]+1) {
        return 40;
    }else{
        return 80;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!section) {
        return 1;
    }else if (section == 1+[dataDict[@"list"] count]) {
        return 1;
    }else{
        int num = 0;
        if ([dataDict[@"list"][section-1][@"CoverCount"] intValue]) {
            num++;
        }

        if ([dataDict[@"list"][section-1][@"PhotoCount"] intValue]) {
            num++;
        }

        if ([dataDict[@"list"][section-1][@"BackCount"] intValue]) {
            num++;
        }

        return num;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!indexPath.section) {
        NSString * cellIde = @"cell0";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
            cell.backgroundColor = UIColorFromRGB(0xebebeb);//[UIColor whiteColor];
//            cell.contentView.backgroundColor = [UIColor whiteColor];
            [cell addSubview:topBtn];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            UIView * line = [[XDTools sharedXDTools] createSeparatorLineWithRect:CGRectMake(0, 59.5f, UI_SCREEN_WIDTH, .5f)];
//            [cell.contentView addSubview:line];

        }
        if ([dataDict[@"AllPhoto"] intValue] == 1) {
            [topBtn setTitle:@"浏览全部底片" forState:UIControlStateNormal];
        }else{
            if (baseIsOK) {
                [topBtn setTitle:@"浏览已选择底片" forState:UIControlStateNormal];
            }else{
                [topBtn setTitle:[NSString stringWithFormat:@"选择底片（%d张/%d张）",0,[dataDict[@"pcount"] intValue]] forState:UIControlStateNormal];
            }
        }
        return cell;

    }else if (indexPath.section == [dataDict[@"list"] count]+1) {

        NSString * cellIde = @"cell2";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];

            UILabel * nameLB = [UILabel initLabelText:@"收货地址" andRect:CGRectMake(20, 10, 100, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:16] andTextColor:UIColorFromRGB(0x453d35) andTextAlignment:NSTextAlignmentLeft];
            [cell.contentView addSubview:nameLB];

            UILabel * statusLB = [UILabel initLabelText:@"未填写" andRect:CGRectMake(UI_SCREEN_WIDTH-80, 10, 50, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:13] andTextColor:UIColorFromRGB(0x999999) andTextAlignment:NSTextAlignmentCenter];
            statusLB.tag = 818127;
            [cell.contentView addSubview:statusLB];

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.contentView.backgroundColor = [UIColor whiteColor];

        }
        UILabel * statusLB = (UILabel *)[cell.contentView viewWithTag:818127];
        if (haveAddress) {
            statusLB.text = @"已完成";
        }else{
            statusLB.text = @"未填写";
        }

        for (int i = 0; i < 2; i++) {
            UIView * line = [[XDTools sharedXDTools] createSeparatorLineWithRect:CGRectMake(0, 39.5f*i, UI_SCREEN_WIDTH, .5f)];
            [cell.contentView addSubview:line];
        }
        return cell;

    }else{

        NSString * cellIde = @"cell1";
        XuanpianTaocanCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
        if (!cell) {
            cell = [[XuanpianTaocanCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }

        NSDictionary * dict = dataDict[@"list"][indexPath.section-1];

        NSString * type = @"";
        if (!indexPath.row) {
            if ([dict[@"CoverCount"] intValue]) {
                type = @"Cover";
            }else{
                if ([dict[@"PhotoCount"] intValue]) {
                    type = @"Photo";
                }else{
                    type = @"Back";
                }
            }
        }else if (indexPath.row == 1) {
            if ([dict[@"CoverCount"] intValue]) {
                if ([dict[@"PhotoCount"] intValue]) {
                    type = @"Photo";
                }else{
                    type = @"Back";
                }
            }else{
                if ([dict[@"BackCount"] intValue]) {
                    type = @"Back";
                }
            }
        }else{
            type = @"Back";
        }

        cell.type = type;

        if (!indexPath.row) {
            cell.topLine.hidden = NO;
        }else{
            cell.topLine.hidden = YES;
        }

        [cell getDataWithDict:dict type:type];

        return cell;
    }

}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section != 1+[dataDict[@"list"] count] && indexPath.section) {
        if (baseIsOK) {
            XuanpianTaocanCell * cell = (XuanpianTaocanCell *)[tableView cellForRowAtIndexPath:indexPath];

            ChooseImageViewController * choose = [[ChooseImageViewController alloc] init];
            choose.orderID = _orderID;
            choose.orderProID = dataDict[@"list"][indexPath.section-1][@"OrderProdID"];
            if ([cell.type isEqualToString:@"Cover"]) {
                choose.maxNumber = dataDict[@"list"][indexPath.section-1][@"CoverCount"];
                if ([dataDict[@"list"][indexPath.section-1][@"CoverHeath"] length]) {
                    choose.canChoose = NO;
                    choose.havePush = YES;
                }else{
                    choose.canChoose = YES;
                }
            }else if ([cell.type isEqualToString:@"Photo"]) {
                choose.maxNumber = dataDict[@"list"][indexPath.section-1][@"PhotoCount"];
                if ([dataDict[@"list"][indexPath.section-1][@"Heath"] length]) {
                    choose.canChoose = NO;
                    choose.havePush = YES;
                }else{
                    choose.canChoose = YES;
                }
            }else{
                choose.maxNumber = dataDict[@"list"][indexPath.section-1][@"BackCount"];
                if ([dataDict[@"list"][indexPath.section-1][@"BackHeath"] length]) {
                    choose.canChoose = NO;
                    choose.havePush = YES;
                }else{
                    choose.canChoose = YES;
                }
            }
            choose.indexNum = indexPath.section-1;

            choose.phototype = cell.type;
            choose.delegate = self;

            choose.titleStr = dataDict[@"list"][indexPath.section-1][@"name"];
            
            [self.navigationController pushViewController:choose animated:YES];

        }else{
            [XDTools showTips:@"请先选择底片" toView:self.contentView];
        }

    }

    if (indexPath.section == 1+[dataDict[@"list"] count]) {
        [self gotoAddress];
    }
}


- (void)topBtnClick{
    ChooseImageViewController * choose = [[ChooseImageViewController alloc] init];
    choose.orderID = _orderID;
    choose.orderProID = @"1";
    choose.maxNumber = dataDict[@"pcount"];
    choose.allCount = dataDict[@"count"];
    choose.phototype = @"Base";
    if ([dataDict[@"AllPhoto"] intValue] == 1) {
        choose.canChoose = NO;
    }else{
        if (baseIsOK) {
            choose.canChoose = NO;
        }else{
            choose.canChoose = YES;
        }
    }
    choose.photoPrice = dataDict[@"PhotoPrice"];
    choose.titleStr = @"全部底片";
    choose.delegate = self;
    [self.navigationController pushViewController:choose animated:YES];
}

//- (void)gotoChooseImage:(UIButton *)sender{
//    ChooseImageViewController * choose = [[ChooseImageViewController alloc] init];
//    choose.orderID = _orderID;
//    choose.orderProID = dataDict[@"list"][sender.tag-983200][@"OrderProdID"];
//    choose.maxNumber = dataDict[@"list"][sender.tag-983200][@"PhotoCount"];
//    choose.indexNum = sender.tag - 983200;
//    if ([dataDict[@"list"][sender.tag-983200][@"BackCount"] intValue]) {
//        choose.phototype = @"Back";
//    }else if ([dataDict[@"list"][sender.tag-983200][@"CoverCount"] intValue]) {
//        choose.phototype = @"Cover";
//    }else{
//        choose.phototype = @"Photo";
//    }
//    choose.canChoose = YES;
//    choose.delegate = self;
//
//    [self.navigationController pushViewController:choose animated:YES];
//}

- (void)gotoAddress{
    AddressViewController * address = [[AddressViewController alloc] init];
    address.orderID = _orderID;
    address.delegate = self;
    [self.navigationController pushViewController:address animated:YES];
}

- (void)chooseImageIsOK{
    if (!baseIsOK) {
        [XDTools showTips:@"请先选择底片" toView:self.contentView];
        return;
    }
    
    for (NSDictionary * dic in dataDict[@"list"]) {
        if ([dic[@"CoverCount"] intValue] && ![dic[@"CoverHeath"] length]) {
            [XDTools showTips:@"请先选择底片" toView:self.contentView];
            return;
        }
        
        if ([dic[@"PhotoCount"] intValue] && ![dic[@"Heath"] length]) {
            [XDTools showTips:@"请先选择底片" toView:self.contentView];
            return;
        }
        
        if ([dic[@"BackCount"] intValue] && ![dic[@"BackHeath"] length]) {
            [XDTools showTips:@"请先选择底片" toView:self.contentView];
            return;
        }
    }
    
    if (!haveAddress) {
        [XDTools showTips:@"请填写收货地址" toView:self.contentView];
        return;
    }
    
    
    [self getDataWithDict:@{@"OrderID":_orderID} api:API_CHOOSEIMAGEOK];
    
}


#pragma mark - ChooseImageViewController Delegate
- (void)havePushIndex:(int)indexNum photo:(NSString *)type photoCover:(NSString *)photoCover{
//    if ([type isEqualToString:@"Base"]) {
//        [topBtn setTitle:[NSString stringWithFormat:@"浏览并选择底片（%d张/%@张）",[dataDict[@"pcount"] intValue],dataDict[@"count"]] forState:UIControlStateNormal];
//        topBtn.userInteractionEnabled = NO;
//        baseIsOK = YES;
//    }else{
//        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:dataDict[@"list"][indexNum]];
//
//        if ([type isEqualToString:@"Cover"]) {
//            [dict setObject:@"YES" forKey:@"CoverOK"];
////            [dict setObject:photoCover forKey:@"CoverHeath"];
//        }else if ([type isEqualToString:@"Photo"]) {
//            [dict setObject:@"YES" forKey:@"PhotoOK"];
////            [dict setObject:photoCover forKey:@"CoverOK"];
//        }else{
//            [dict setObject:@"YES" forKey:@"BackOK"];
////            [dict setObject:photoCover forKey:@"CoverOK"];
//        }
//
//        NSMutableArray * array = [NSMutableArray arrayWithArray:dataDict[@"list"]];
//        [array replaceObjectAtIndex:indexNum withObject:dict];
//        [dataDict setObject:array forKey:@"list"];
//
//        [myTableView reloadData];
//
//
//    }

    
}

- (void)addressIsOK{
    haveAddress = YES;
    [myTableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    _needFresh = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
